package com.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.sql.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.DateUtil;
import util.IdGenerator;
import util.Validation;

import model.CompensationLeaveDTO;
import model.LeaveDTO;
import model.LeaveTypeDTO;
import model.Status;
import model.UserDTO;

import exception.DAOSystemException;

import bizlogic.CompensationLeaveManager;
import bizlogic.LeaveManager;
import bizlogic.LeaveTypeManager;
import bizlogic.UserManager;

/**
 * Servlet implementation class SubmitLeaveServlet
 */
@WebServlet("/SubmitLeaveServlet")
public class SubmitLeaveServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SubmitLeaveServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		RequestDispatcher rd = request.getRequestDispatcher("SubmitLeave.jsp");
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			doProcess(request, response);
		} catch (DAOSystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void doProcess(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			DAOSystemException {
		// TODO Auto-generated method stub
		String id = IdGenerator.generateLeavID().toString();
		System.out.println("New ID generated is ---->" + id);
		UserDTO us =(UserDTO)request.getSession().getAttribute("user");
		String userId = us.getId().toString();
        String pleavetype=request.getParameter("leaveType");
		java.sql.Date from = DateUtil
				.stringToDATE(request.getParameter("from"));
		java.sql.Date to = DateUtil.stringToDATE(request.getParameter("to"));
		boolean isStartHoliday = Validation.isHolidayDate(from);
		boolean isEndHoliday = Validation.isHolidayDate(from);
		
		boolean diff = Validation.isDateDiffBig(to, from);

		if ((isStartHoliday || isEndHoliday || diff)&& !(pleavetype.equals("Compensation Leave"))  ) 
		{
			String msg = "start date or end date canot be a holiday, difference cannot be 14 days or more";
			request.setAttribute("msg", msg);
			RequestDispatcher rd = request.getRequestDispatcher("SubmitLeave.jsp");
			rd.forward(request, response);
		} 
		else if(pleavetype.equals("Compensation Leave")) {
			System.out.print("inside comp");
			long totalNumberOfDays = Validation.getDateDiff(to, from);
			java.sql.Date cloopdate =from;
			int holidaycnt=0;
			Calendar c=Calendar.getInstance();
			c.set(cloopdate.getYear(), cloopdate.getMonth(), cloopdate.getDate());
			int d= cloopdate.getDate();
			while (d<=to.getDate())
			{
				if ((Validation.isHolidayDate(cloopdate)) || ( DateUtil.getDayOfWeek(c)=="Sunday"  ||  DateUtil.getDayOfWeek(c)=="Saturday") )
				
				{
					holidaycnt=holidaycnt+1;
				}
				d=d+1;
				
			}
			long currentOTdays=totalNumberOfDays-holidaycnt;
			CompensationLeaveDTO cldto= new CompensationLeaveManager().findCompensationLeave(userId);
			double entitle=(cldto.getTotalOT()-cldto.getConsumeOT())/8.0d;
			System.out.print(""+holidaycnt);
			if ((currentOTdays >entitle)|| (cldto.getId()== null) )
			{
				String msg = "Not entitle to claim compensation greater than available claimable days : "+(cldto.getTotalOT()-cldto.getConsumeOT())/8.0d;
				request.setAttribute("msg", msg);
				RequestDispatcher rd = request.getRequestDispatcher("SubmitLeave.jsp");
				rd.forward(request, response);
			}
			else
			{
				doInsert(request,response,id,from,to);
			}
			
		}
		else {
			doInsert(request,response,id,from,to);
		}
	}

	private void doInsert(HttpServletRequest request,
			HttpServletResponse response,String id, Date from, Date to ) throws ServletException, IOException {
		UserDTO us =(UserDTO)request.getSession().getAttribute("user");
		String userId = us.getId().toString();
		String reason = request.getParameter("reason");
		String leaveNature = request.getParameter("leaveNature");
		String workDissemination = request
				.getParameter("workDissemination");
		String contactDetails = request.getParameter("contactDetails");
		String leaveType = request.getParameter("leaveType");
		System.out.println("Leave Type......" + leaveType);

		Calendar cal = Calendar.getInstance();
		java.sql.Date dat = DateUtil.convertCalenderToSqlDate(cal);

		LeaveTypeManager leaveTypeMgr = new LeaveTypeManager();
		UserManager userMgr = new UserManager();
		LeaveTypeDTO leaveTypeDTO = null;
		UserDTO userDTO = null;
		try {
			leaveTypeDTO = leaveTypeMgr.findLeaveType(leaveType);
			userDTO = userMgr.findUser(userId);
		} catch (DAOSystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		LeaveManager leaveMgr = new LeaveManager();

		try {
			leaveMgr.insertLeave(new LeaveDTO(id, from, to, Status.APPLIED,
					reason, leaveNature, workDissemination, contactDetails,
					leaveTypeDTO, userDTO, dat));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String msg = "sucessssssss";
		request.setAttribute("msg", msg);
		RequestDispatcher rd = request.getRequestDispatcher("SubmitLeave.jsp");
		rd.forward(request, response);
		
	}

/*	private java.sql.Date getDate(String dateString) {
		String[] dateArray = dateString.split("-");
		java.sql.Date date = new java.sql.Date(
				Integer.parseInt(dateArray[0]) - 1900,
				Integer.parseInt(dateArray[1]) - 1,
				Integer.parseInt(dateArray[2]));
		return date;
	}*/
}
